package com.auto.survey.activity.monitoring.obj

import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.auto.survey.R
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.adapter.MontoringObjectAdapter
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ManagerObjectActivity:BaseActivity() {

    private val database = MonitoringRepository()
    private val adapter = MontoringObjectAdapter(this)
    private var projectId:Int = -1

    override fun initView() {

        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.blue)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.blue)

        lifecycleScope.launch {
            val project = database.getProjectById(projectId)
            withContext(Dispatchers.Main) {
                if (project != null) {
                    mComment_title?.setTitle(project.montoringProjectName)
                } else {
                    mComment_title?.setTitle("监测对象列表")
                }
            }
        }

        mComment_title?.setRightTitle("添加监测对象")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{
            val intent = Intent()
            intent.putExtra(KEY_INTENT_PROJET_ID,projectId)
            intent.setClass(this@ManagerObjectActivity, CreateObjectActivity::class.java)
            startActivity(intent)
        })

        val rv_objects = findViewById<RecyclerView>(R.id.rv_manager_montoring_project)
        rv_objects.layoutManager = LinearLayoutManager(this)
        rv_objects.adapter = adapter

    }

    override fun onResume() {
        super.onResume()

        lifecycleScope.launch {
            database.getObjectsByProjectId(projectId).collect {
                adapter.setItems(it)
            }
        }

    }

    override fun getLayoutId(): Int {

        return R.layout.activity_manager_montoring_project
    }
}